package com.net.xpay.common.service.impl;

import com.google.common.base.Preconditions;
import com.net.xpay.common.domain.partner.Partner;
import com.net.xpay.common.domain.stat.PartnerRealTimeStat;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.common.manager.stat.PartnerRealTimeStatManager;
import com.net.xpay.core.manager.ChargeRecordManager;
import com.net.xpay.core.manager.PayTransBatchManager;
import com.net.xpay.core.manager.safePay.SafePayBatchManager;
import com.net.xpay.core.model.PartnerUserPayTransDayStatModel;
import com.net.xpay.core.model.PartnerUserSafePayTransDayStatModel;
import com.net.common.util.LocalDateUtil;
import com.net.xpay.common.manager.partner.PartnerManager;
import com.net.xpay.common.service.PartnerRealTimeStatService;
import com.net.shard.ShardDataSource;
import com.net.shard.ShardDataSourceConfigurer;
import com.net.shard.ShardUtil;
import com.net.shard.domain.ShardConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PartnerRealTimeStatServiceImpl implements PartnerRealTimeStatService {
    @Autowired
    private PayTransBatchManager payTransBatchManager;

    @Autowired
    private SafePayBatchManager safePayBatchManager;

    @Autowired
    private UserManager userManager;

    @Autowired
    private ChargeRecordManager chargeRecordManager;

    @Autowired
    private PartnerRealTimeStatManager partnerRealTimeStatManager;

    @Autowired
    private PartnerManager partnerManager;

    @Autowired
    @Qualifier("shardDataSource")
    private DataSource shardDataSource;


    @Override
    public void statPartnerRealTimeStat(LocalDateTime time) {
        List<Partner> partnerList = partnerManager.listAll();
        for (Partner partner : partnerList) {
            try {
                doPartnerRealTimeStat(partner.getId(), time);
            } catch (Exception e) {
                log.error("statPartnerRealTimeStat error|partnerId={}", partner.getId(), e);
            }
        }
    }

    @Override
    public void doPartnerRealTimeStat(Long partnerId, LocalDateTime time) {
        ShardDataSourceConfigurer shardDataSourceConfigurer = ((ShardDataSource) shardDataSource).getShardDataSourceConfigurer();
        Map<Long, ShardConfig> shardConfigMap = shardDataSourceConfigurer.getShardConfigMap();
        Preconditions.checkArgument(CollectionUtils.isNotEmpty(shardConfigMap.keySet()));

        PartnerRealTimeStat stat = PartnerRealTimeStat.getInstance(partnerId, time);
        //统计查询
        //user表统计
        // 获取当天的起始时间和终止时间 终止时间保留在当前时间
        LocalDateTime minEndTime= LocalDateUtil.getDayStart(time);
        long registerCount = userManager.countRegister(partnerId, minEndTime, time);
        stat.setRegisterCount(registerCount);
        for (Long shardId : shardConfigMap.keySet()) {
            try {
                ShardUtil.setShardContext(shardId);
                log.info("doPartnerRealTimeStat start in shard={}|partnerId={}", shardId, partnerId);
                doStatInShard(stat, partnerId, minEndTime, time);
                log.info("doPartnerRealTimeStat end in shard={}|partnerId={}", shardId, partnerId);
            } finally {
                ShardUtil.cleanShardContext();
            }
        }

        PartnerRealTimeStat beforeStat = partnerRealTimeStatManager.getByPartnerId(partnerId);
        if (beforeStat != null) {
            stat.setId(beforeStat.getId());
            partnerRealTimeStatManager.update(stat);
        } else {
            partnerRealTimeStatManager.save(stat);
        }
    }

    //每个库，数据在里面叠加
    private void doStatInShard(PartnerRealTimeStat stat, Long partnerId, LocalDateTime minEndTime, LocalDateTime maxEndTime) {
        //chargeRecord表统计
        long serviceChargeFee = chargeRecordManager.sumServiceChargeFeeByDay(partnerId, minEndTime, maxEndTime);
        //payTransBatch表统计
        PartnerUserPayTransDayStatModel partnerUserPayTransDayStatModel = payTransBatchManager.sumPartnerPayTransDay(partnerId, minEndTime, maxEndTime);
        //safePayTransBatch表统计
        PartnerUserSafePayTransDayStatModel safePayTransDayStatModel = safePayBatchManager.sumPartnerSafePayTransDay(partnerId, minEndTime, maxEndTime);

        BigDecimal finalServiceChargeFee = new BigDecimal(serviceChargeFee).multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP);
        stat.setServiceChargeFee(stat.getServiceChargeFee().add(finalServiceChargeFee));
        //服务费支出
        stat.setPayTransServicePrice(stat.getPayTransServicePrice().add(new BigDecimal(partnerUserPayTransDayStatModel.getPayTransServicePrice()).multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP)));
        stat.setSafePayTransServicePrice(stat.getSafePayTransServicePrice().add(new BigDecimal(safePayTransDayStatModel.getSafePayTransServicePrice()).multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP)));
        stat.setTotalServicePrice(stat.getPayTransServicePrice().add(stat.getSafePayTransServicePrice()));
        //转账笔数
        stat.setSafePayTransCount(stat.getSafePayTransCount() + partnerUserPayTransDayStatModel.getPayTransCount());
        stat.setPayTransCount(stat.getPayTransCount() + partnerUserPayTransDayStatModel.getPayTransCount());
        stat.setTotalCount(stat.getPayTransCount() + stat.getSafePayTransCount());
        //总金额
        stat.setPayTransAmount(stat.getPayTransAmount().add(partnerUserPayTransDayStatModel.getPayTransAmount()));
        stat.setSafePayTransAmount(stat.getSafePayTransAmount().add(safePayTransDayStatModel.getSafePayTransAmount()));
        stat.setTotalTransAmount(stat.getPayTransAmount().add(stat.getSafePayTransAmount()));
        //成功金额
        stat.setPayTransSuccessAmount(stat.getPayTransSuccessAmount().add(partnerUserPayTransDayStatModel.getPayTransSuccessAmount()));
        stat.setSafePayTransSuccessAmount(stat.getSafePayTransSuccessAmount().add(safePayTransDayStatModel.getSafePayTransSuccessAmount()));
        stat.setTotalSuccessTransAmount(stat.getPayTransSuccessAmount().add(stat.getSafePayTransSuccessAmount()));
        //成功笔数
        stat.setPayTransSuccessCount(stat.getPayTransSuccessCount() + partnerUserPayTransDayStatModel.getPayTransSuccessCount());
        stat.setSafePayTransSuccessCount(stat.getSafePayTransSuccessCount() + safePayTransDayStatModel.getSafePayTransSuccessCount());
        stat.setTotalSuccessCount(stat.getPayTransSuccessCount() + stat.getSafePayTransSuccessCount());
        //失败金额
        stat.setPayTransFailAmount(stat.getPayTransFailAmount().add(partnerUserPayTransDayStatModel.getPayTransFailAmount()));
        stat.setSafePayTransFailAmount(stat.getSafePayTransFailAmount().add(safePayTransDayStatModel.getSafePayTransFailAmount()));
        stat.setTotalFailTransAmount(stat.getPayTransFailAmount().add(stat.getSafePayTransFailAmount()));
        //失败笔数
        stat.setPayTransFailCount(stat.getPayTransFailCount() + partnerUserPayTransDayStatModel.getPayTransFailCount());
        stat.setSafePayTransFailCount(stat.getSafePayTransFailCount() + safePayTransDayStatModel.getSafePayTransFailCount());
        stat.setTotalFailCount(stat.getPayTransFailCount() + stat.getSafePayTransFailCount());
    }


}
